/* eslint-disable camelcase */
import { observable, autorun, action, runInAction, computed } from 'mobx';
import { DbUtils } from '../utils/dbUtils';

import speech_0 from './json/speech_0.json';
import speech_1 from './json/speech_1.json';
import speech_2 from './json/speech_2.json';
import speech_3 from './json/speech_3.json';
import speech_4 from './json/speech_4.json';
import speech_5 from './json/speech_5.json';
import speech_6 from './json/speech_6.json';
import speech_7 from './json/speech_7.json';
import speech_8 from './json/speech_8.json';
import speech_9 from './json/speech_9.json';

const DELETE_SPEECH = 'DELETE FROM speech;'
const COUNT_SPEECH = 'select count(*) as countSpeech from speech;'
const CREATE_SPEECH = 'CREATE TABLE IF NOT EXISTS speech (id integer PRIMARY KEY NOT NULL, title text, title1 text, title2 text, content text, full_content text,types text);'

const SQL_SAVE = 'insert into speech (title, title1, title2, content, full_content, types) values (?, ?, ?, ?, ?, ?)'
const SQL_LIST_CATEGORY = 'SELECT DISTINCT title1 from speech;'
const SQL_SEARCH_WITH_TITLE = 'SELECT * FROM speech WHERE title2 LIKE ? AND content LIKE ? ORDER BY id ASC LIMIT ? OFFSET ?;'

class SpeechStore {
    totalRecords = 11430
    @observable currTotal = -1
    @observable categoryList = []

    @observable searchText = null
    @observable searchList = []
    @observable hasMore = true
    @observable loading = false

    constructor() {

    }

    get isLoading() {
        return this.currTotal != this.totalRecords
    }

    get loadingPercent() {
        return Number((100 * this.currTotal / this.totalRecords).toFixed(0))
    }

    @action loadSpeechList() {
        DbUtils.call(CREATE_SPEECH, null, (flag, _) => {
            DbUtils.call(COUNT_SPEECH, null, (flag, { rows }) => {
                let countSpeech = rows.item(0).countSpeech

                if (countSpeech == 0) {
                    this.currTotal = 0
                    runInAction(() => {
                        this.saveFromLocal()
                    })
                } else if (countSpeech == this.totalRecords) {//全部数据都存在
                    this.currTotal = countSpeech
                    runInAction(() => {
                        this.loadCategory()
                    })
                } else {
                    DbUtils.call(DELETE_SPEECH, null, (flag, _) => {
                        runInAction(() => {
                            this.currTotal = 0
                            this.saveFromLocal()
                        })
                    })
                }
            })
        })
    }

    @action saveFromLocal() {
        const jsonDatas = [
            speech_0, speech_1, speech_2,
            speech_3, speech_4, speech_5,
            speech_6, speech_7, speech_8,
            speech_9
        ]

        jsonDatas.forEach(jsonData => {
            jsonData.forEach(subCategoryJson => {
                // 某一类下的 speech 集合
                let speechs = subCategoryJson['data']
                speechs.forEach(speech => {
                    // {
                    //     "is_read": "0",
                    //     "title": "拍照搭讪法",
                    //     "browse": "17",
                    //     "title1": "幽默恋爱情话",
                    //     "tongue_type_id": "5",
                    //     "ids": "78550",
                    //     "content": "男：能不能和我拍个照\n 女：为什么？\n 男：我要向我同事证明，天使是存在的（搭讪开场白）",
                    //     "source": "生活",
                    //     "title2": "搭讪开场白",
                    //     "praise": "0",
                    //     "type_id": "2",
                    //     "full_content": "男：能不能和我拍个照\n 女：为什么？\n 男：我要向我同事证明，天使是存在的（搭讪开场白）拍照搭讪法",
                    //     "is_white": "2",
                    //     "id": 1,
                    //     "types": "惯例"
                    // },

                    const { title, title1, title2, content, full_content, types } = speech

                    DbUtils.call(
                        SQL_SAVE,
                        [title, title1, title2, content, full_content, types],
                        (flag, result) => {
                            // console.log(`数据${result.insertId}添加`, flag ? '成功' : '失败')
                            if (flag) {
                                runInAction(() => {
                                    this.currTotal++
                                    if (this.currTotal == this.totalRecords) {
                                        this.loadCategory()
                                    }
                                })
                            }
                        }
                    )

                })
            });
        })
    }

    @action
    loadCategory() {
        DbUtils.call(
            SQL_LIST_CATEGORY,
            null,
            (flag, { rows }) => {
                // 本地存放的大类名称列表
                let localSpeechCategory = require('./json/speech.json')
                let dbTitles = []
                for (let i = 0; i < rows.length; i++) {
                    dbTitles.push(rows.item(i).title1)
                }
                let newData = localSpeechCategory.map(item => {
                    return {
                        title: item.filePrefix,
                        data: [...item.data],
                        loadComplete: dbTitles.indexOf(item.filePrefix) != -1,
                    }
                })
                runInAction(() => {
                    this.categoryList = newData
                })
            }
        )
    }

    /**
     * 通过输入内容搜索
     * @param {string} title 分组名称可为空
     * @param {string} content 输入的内容
     * @param {number} page 页数
     * @param {number} size 每页数量
     */
    @action searchByContent(title = '', content = '', page = 1, size = 12) {
        this.loading = true
        this.searchText = content
        let params = [`%${title}%`, `%${content}%`, size, size * (page - 1)]
        DbUtils.call(SQL_SEARCH_WITH_TITLE, params, (flag, result) => {
            runInAction(() => {
                let newData = []
                for (let i = 0; i < result.rows.length; i++) {
                    newData.push(result.rows.item(i))
                }
                if (page == 1) {
                    this.searchList = newData
                } else {
                    this.searchList.push(...newData)
                }
                this.hasMore = result.rows.length == size
                this.loading = false
            })
        })
    }

    @computed get formattedCategoryList() {
        return this.categoryList.map((v) => {
            return {
                title: v.title,
                data: [v.data.slice()],
            }
        }).slice()
    }

    @computed get formattedSearchList() {
        return this.searchList.map((v) => {
            return { ...v }
        }).slice()
    }
}

let store = new SpeechStore()

/* 观察状态改变的函数 */
// autorun(function () {
//     console.log(
//         `searchList = ${store.formattedSearchList};`,
//     );
// }, { delay: 500 });

export default store